package com.developer.platform.application.command;

import cn.hutool.core.bean.BeanUtil;
import com.developer.platform.application.command.cmd.UserAdd;
import com.developer.platform.application.command.cmd.UserAndRoleUpdate;
import com.developer.platform.application.command.cmd.UserPasswordUpdate;
import com.developer.platform.application.command.cmd.UserUpdate;
import com.developer.platform.domain.User;
import com.developer.platform.domain.service.ISecurityService;
import com.developer.platform.domain.service.IUserService;
import com.veeker.core.exceptions.BusinessException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author ：qiaoliang
 * @date ：2020-11-09
 */
@Component
public class UserCmdManager {

    private final IUserService userService;
    private final ISecurityService securityService;

    public UserCmdManager(IUserService userService,
                          ISecurityService securityService) {
        this.userService = userService;
        this.securityService = securityService;
    }

    /**
     * 新增用户信息
     *
     * @author ：qiaoliang
     * @param userAdd : 用户信息
     * @date 2020-10-28 13:41
     */
    @Transactional(rollbackFor = Exception.class, noRollbackFor = BusinessException.class)
    public void save(UserAdd userAdd){
        User user = new User();
        BeanUtil.copyProperties(userAdd, user);
        userService.save(user, userAdd.getRoleIds());
    }


    /**
     * 修改用户信息
     *
     * @author ：qiaoliang
     * @param id : 用户ID
     * @param userAndRoleUpdate : 用户信息
     * @date 2020-10-28 14:03
     */
    @Transactional(rollbackFor = Exception.class, noRollbackFor = BusinessException.class)
    public void update(long id, UserAndRoleUpdate userAndRoleUpdate){
        User user = new User(id);
        BeanUtil.copyProperties(userAndRoleUpdate, user);
        userService.update(user, userAndRoleUpdate.getRoleIds());
    }

    /**
     * 修改个人信息
     *
     * @author ：qiaoliang
     * @param userUpdate : 用户信息
     * @date 2020-10-28 14:03
     */
    public void update(UserUpdate userUpdate){
        User user = new User(securityService.getUserDetailsUserId());
        BeanUtil.copyProperties(userUpdate, user);
        userService.update(user);
    }

    /**
     * 修改用户状态
     *
     * @author ：qiaoliang
     * @param id : 用户ID
     * @date 2020-10-28 14:12
     */
    public void updateStatus(long id){
        userService.updateStatus(id);
    }

    /**
     * 修改个人密码
     *
     * @author ：qiaoliang
     * @param userPasswordUpdate : 密码信息
     * @date 2020-11-09 13:25
     */
    public void updatePassword(UserPasswordUpdate userPasswordUpdate){
        userService.updatePassword(securityService.getUserDetailsUserId(), userPasswordUpdate.getNewPassword(),
                userPasswordUpdate.getOldPassword());
    }

}
